<template>
  <ElDialog v-model="dialogVisible" title="题目扩展" :width="1000" align-center>
    <!-- 表格头部 -->
    <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
      <template #left>
        <ElSpace wrap>
          <ElButton @click="addDialog" v-ripple>绑定扩展</ElButton>
        </ElSpace>
      </template>
    </ArtTableHeader>

    <!-- 表格 -->
    <ArtTable
      :loading="loading"
      :data="data"
      :columns="columns"
      empty-height="330px"
      :max-height="500"
      :pagination="undefined"
    >
      <template #subjectExtContent="{ row }"><div v-html="row.subjectExtContent"></div></template>
      <!-- 设置另见 -->
      <template #bindType="{ row }">
        <ElSwitch
          :model-value="row.subjectExtBindType"
          :active-value="1"
          :inactive-value="0"
          @update:modelValue="changeBindType(row)"
        ></ElSwitch>
      </template>
    </ArtTable>

    <selectExt
      v-model:visible="selectExtVisiable"
      :no-ids="noIds"
      :subject-id="subjectId"
      @submit="getData"
    ></selectExt>
  </ElDialog>
</template>
<script setup lang="ts">
  import {
    apiDeleteSubjectExtBind,
    apiGetSubjectBindExt,
    apiUpdateSubjectExtBindType
  } from '@/api/subject'
  import { useTable } from '@/composables/useTable'
  import { tagType } from '@/maps'
  import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import selectExt from './selectExt.vue'

  const props = withDefaults(
    defineProps<{
      //显示状态
      visible: boolean
      //题目id
      subjectId: number
    }>(),
    {
      visible: false
    }
  )

  const selectExtVisiable = ref(false)
  //不包含的id集合
  const noIds = ref<number[]>()

  const emit = defineEmits<{
    (e: 'update:visible', value: boolean): void
  }>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  //获取数据
  const getList = async () => {
    noIds.value = []
    if (props.subjectId > 0) {
      const res = await apiGetSubjectBindExt(props.subjectId)
      if (res && Array.isArray(res)) {
        noIds.value = res.map((item: any) => item.subjectExtId)
      }
      return res
    }
    return Promise.reject(false)
  }

  //删除数据
  const deleteRecord = (row: any) => {
    ElMessageBox.confirm('确定要删除吗？<p>删除后无法恢复，请谨慎操作！</p>', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }).then(() => {
      // console.log('删除')
      apiDeleteSubjectExtBind({
        id: row.id
      }).then((res) => {
        if (res) {
          ElMessage.success('删除成功')
          getData()
        } else {
          ElMessage.success('删除失败')
        }
      })
    })
  }

  const { columns, data, loading, getData, columnChecks, refreshData } = useTable({
    // 核心配置
    core: {
      apiFn: getList,
      columnsFactory: () => [
        { type: 'index', width: 60, label: '序号', align: 'center' }, // 序号
        {
          prop: 'subjectExtType',
          label: '类型',
          width: 100,
          align: 'center',
          formatter: (row: any) => {
            return h(ElTag, { type: tagType[row.subjectExtType] }, () => row.subjectExtTypeName)
          }
        },
        {
          prop: 'bindType',
          label: '是否另见',
          align: 'center',
          width: 100,
          useSlot: true
        },
        {
          prop: 'subjectExtTitle',
          label: '名称',
          align: 'center',
          width: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'subjectExtContent',
          label: '内容',
          useSlot: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 80,
          fixed: 'right', // 固定列
          align: 'center',
          formatter: (row: any) =>
            h('div', [
              h(ArtButtonTable, {
                type: 'delete',
                title: '删除',
                onClick: () => deleteRecord(row)
              })
            ])
        }
      ]
    }
  })

  //更新另见
  const changeBindType = (row: any): Promise<boolean> => {
    return new Promise((resolve, reject) => {
      const value = row.subjectExtBindType == 1 ? 0 : 1
      apiUpdateSubjectExtBindType({
        id: row.id,
        type: value
      }).then((res) => {
        if (res) {
          ElMessage.success('操作成功')
          row.subjectExtBindType = value
          resolve(true)
        } else {
          reject(true)
        }
      })
    })
  }

  const addDialog = () => {
    selectExtVisiable.value = true
  }

  watch(
    () => props.subjectId,
    (newValue) => {
      if (newValue > 0) {
        noIds.value = []
        getData()
      }
    }
  )
</script>
